package com.gzc.just.play.last.war.centralserver.character.service;

import com.gzc.just.play.last.war.centralserver.character.model.Character;
import com.gzc.just.play.last.war.centralserver.character.repository.CharacterRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 角色管理服务
 * 替代C++的SSCharacterMgr
 */
@Service("central-characterService")
@Transactional
public class CharacterService {
    private static final Logger logger = LoggerFactory.getLogger(CharacterService.class);
    
    @Autowired
    private CharacterRepository characterRepository;
    
    /**
     * 创建新角色
     */
    public Map<String, Object> createCharacter(Long userId, String characterName, Integer characterClass) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查角色名是否已存在
            Optional<Character> existing = characterRepository.findByUserIdAndCharacterName(userId, characterName);
            if (existing.isPresent()) {
                result.put("success", false);
                result.put("message", "角色名已存在");
                return result;
            }
            
            // 检查用户是否已有3个角色（假设限制为3）
            List<Character> userCharacters = characterRepository.findByUserId(userId);
            if (userCharacters.size() >= 3) {
                result.put("success", false);
                result.put("message", "角色数量已达到上限");
                return result;
            }
            
            // 创建新角色
            Character newCharacter = new Character();
            newCharacter.setUserId(userId);
            newCharacter.setCharacterName(characterName);
            newCharacter.setCharacterClass(characterClass);
            newCharacter.setLevel(1);
            newCharacter.setExp(0L);
            newCharacter.setAttack(10);
            newCharacter.setDefense(10);
            newCharacter.setHealth(100);
            newCharacter.setMaxHealth(100);
            newCharacter.setSpeed(10);
            newCharacter.setIntelligence(10);
            newCharacter.setStamina(100);
            newCharacter.setIsMain(userCharacters.isEmpty());  // 如果是第一个角色，设为主角
            newCharacter.calculateBattlePower();
            
            Character savedCharacter = characterRepository.save(newCharacter);
            
            result.put("success", true);
            result.put("message", "角色创建成功");
            result.put("character", savedCharacter);
            
            logger.info("Character created: {} for user {}", characterName, userId);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "角色创建失败：" + e.getMessage());
            logger.error("Create character error", e);
        }
        
        return result;
    }
    
    /**
     * 获取用户的所有角色
     */
    public List<Character> getUserCharacters(Long userId) {
        return characterRepository.findByUserId(userId);
    }
    
    /**
     * 获取角色信息
     */
    public Character getCharacter(Long characterId) {
        return characterRepository.findById(characterId).orElse(null);
    }
    
    /**
     * 更新角色信息
     */
    public Character updateCharacter(Character character) {
        character.calculateBattlePower();
        return characterRepository.save(character);
    }
    
    /**
     * 设置主角色
     */
    public Map<String, Object> setMainCharacter(Long userId, Long characterId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取旧的主角色
            Optional<Character> oldMain = characterRepository.findByUserIdAndIsMainTrue(userId);
            oldMain.ifPresent(c -> {
                c.setIsMain(false);
                characterRepository.save(c);
            });
            
            // 设置新主角色
            Character newMain = characterRepository.findById(characterId).orElse(null);
            if (newMain != null && newMain.getUserId().equals(userId)) {
                newMain.setIsMain(true);
                characterRepository.save(newMain);
                
                result.put("success", true);
                result.put("message", "主角色设置成功");
            } else {
                result.put("success", false);
                result.put("message", "角色不存在或不属于该用户");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置主角色失败：" + e.getMessage());
            logger.error("Set main character error", e);
        }
        
        return result;
    }
    
    /**
     * 获取用户的主角色
     */
    public Character getMainCharacter(Long userId) {
        Optional<Character> mainCharacter = characterRepository.findByUserIdAndIsMainTrue(userId);
        if (mainCharacter.isEmpty()) {
            // 如果没有主角色，获取第一个
            List<Character> characters = characterRepository.findByUserId(userId);
            if (!characters.isEmpty()) {
                Character firstChar = characters.get(0);
                firstChar.setIsMain(true);
                return characterRepository.save(firstChar);
            }
        }
        return mainCharacter.orElse(null);
    }
    
    /**
     * 增加角色经验
     */
    public void addCharacterExp(Long characterId, long expAmount) {
        Character character = characterRepository.findById(characterId).orElse(null);
        if (character != null) {
            character.addExp(expAmount);
            
            // 检查升级
            long expPerLevel = 1000;
            int newLevel = (int) (1 + character.getExp() / expPerLevel);
            if (newLevel > character.getLevel()) {
                character.setLevel(newLevel);
                logger.info("Character {} leveled up to {}", characterId, newLevel);
            }
            
            characterRepository.save(character);
        }
    }
    
    /**
     * 增加角色属性
     */
    public void addCharacterStat(Long characterId, String statType, int amount) {
        Character character = characterRepository.findById(characterId).orElse(null);
        if (character != null) {
            character.addStat(statType, amount);
            characterRepository.save(character);
        }
    }
    
    /**
     * 删除角色
     */
    public Map<String, Object> deleteCharacter(Long userId, Long characterId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Character character = characterRepository.findById(characterId).orElse(null);
            if (character == null || !character.getUserId().equals(userId)) {
                result.put("success", false);
                result.put("message", "角色不存在或不属于该用户");
                return result;
            }
            
            // 如果是主角色，不允许删除（或转换主角色）
            if (character.getIsMain()) {
                List<Character> otherCharacters = characterRepository.findByUserId(userId);
                if (otherCharacters.size() <= 1) {
                    result.put("success", false);
                    result.put("message", "不能删除唯一的主角色");
                    return result;
                }
                
                // 转换主角色
                Character newMain = otherCharacters.stream()
                    .filter(c -> !c.getCharacterId().equals(characterId))
                    .findFirst()
                    .orElse(null);
                if (newMain != null) {
                    newMain.setIsMain(true);
                    characterRepository.save(newMain);
                }
            }
            
            characterRepository.deleteById(characterId);
            result.put("success", true);
            result.put("message", "角色删除成功");
            
            logger.info("Character deleted: {} for user {}", characterId, userId);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "角色删除失败：" + e.getMessage());
            logger.error("Delete character error", e);
        }
        
        return result;
    }
    
    /**
     * 获取用户最强角色
     */
    public Character getStrongestCharacter(Long userId) {
        Optional<Character> strongest = characterRepository.findStrongestCharacter(userId);
        return strongest.orElse(null);
    }
}
